<template>
    <div class="mooc-set-page">
        <div class="topic-title">{{detail.name}}</div>
        <div class="selected-topic">
            <div class="sort-left">
                <div class="selected-mooc">
                    <!-- <span class="topic-label">已选慕课</span> -->
                    <span class="topic-desc">您已添加<span class="topic-num">{{moocList.length}}</span>门慕课，其中必修<span class="topic-num">{{mustStudy}}</span>门，选修<span class="topic-num">{{unMustStudy}}</span>门</span>
                </div>
                <div class="complete-rule">
                    <el-form ref="editRef" :model="formData" :rules="formRule" :hide-required-asterisk="true" :inline="true" label-width="0">
                        <el-form-item label="">
                            <span>，请设置选修课需要完成</span>
                            <el-input 
                                ref="coureNumRef"
                                class="lesson-num" 
                                maxlength="50" 
                                type="text" 
                                v-model.number.trim="formData.courseNum">
                            </el-input>
                            <span>门</span>
                        </el-form-item>
                        <el-form-item label="" prop="courseNum" class="error-item"></el-form-item>
                    </el-form>
                </div>
            </div>
            <el-button class="srt-el-button srt-el-button-h32 select-mooc-btn" @click="selectMooc">添加慕课</el-button>
        </div>
        <el-table :data="moocList" style="width: 100%" class="srt-border-table mooc-table" empty-text="还没有添加慕课" border>
            <el-table-column type="index" label="序号" width="87" />
            <el-table-column prop="cover" label="慕课名称" width="455">
                <template #default="scope">
                    <div class="cursor mooc-title">
                        <Ellipsis :content="scope.row.title" :rows="1" :lineHeight="22"/>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="title" label="慕课分类" width="183">
                <template #default="scope">
                    <div>
                        <Ellipsis v-if="scope.row.classifyList&&scope.row.classifyList.length" :content="scope.row.classifyList[0].name" :rows="1" :lineHeight="22"/>
                        <span v-else>-</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="lecturerList" label="选修设置" width="250px">
                <template #default="scope">
                    <el-radio v-model="scope.row.required" class="srt-el-radio" :label="1">必修</el-radio>
                    <el-radio v-model="scope.row.required" class="srt-el-radio" :label="0">选修</el-radio>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button v-if="scope.$index" class="srt-el-button srt-el-button--link srt-el-button-h28" @click="handleMooc('up', scope.row, scope.$index)">上移</el-button>
                    <el-button v-if="scope.$index != moocList.length-1" class="srt-el-button srt-el-button--link srt-el-button-h28" @click="handleMooc('down', scope.row, scope.$index, scope)">下移</el-button>
                    <el-button class="srt-el-button srt-el-button--link srt-el-button-h28" @click="handleMooc('delete', scope.row, scope.$index)">移除</el-button>
                </template>
            </el-table-column>
            <template #empty>
                <div class="t-empty-wrap">
                    <NoData info="还没有添加慕课" url="no-course.png" />
                    <el-button class="srt-el-button srt-el-button-h32 select-mooc-btn add-mooc-btn" @click="selectMooc">添加慕课</el-button>
                </div>
            </template>
        </el-table>
    </div>
    <div class="submit">
        <el-button class="srt-el-button srt-el-button--cancel srt-el-button-h36 up-step" type="" @click="changeStep(1)">上一步</el-button>
        <el-button class="srt-el-button srt-el-button--primary srt-el-button-h36" type="primary" @click="save">确定</el-button>
    </div>
    
    <!-- 在线编辑 -->
    <SelectMoocDialog v-model="showSelectMooc" :mooc-list="moocList" @update-content="addMooc"/>
</template>

<script setup>
import Ellipsis from '@/components/ellipsis.vue';
import { ref, computed, onMounted, watch } from 'vue'
import Confirm from '@/components/confirm/confirm.js'
import SelectMoocDialog from './dialog/select-mooc.vue';
import NoData from '@/components/no-data.vue';
import {useStore} from 'vuex';
import {useRoute} from 'vue-router';
import { pageJump } from '@/global/location-transfer';
import { jumpHref } from '@/router/jumpHref';
import { queryToJson } from '@/lib/tools';

const route = useRoute()

const props = defineProps({
    moocTopic: {
        type: Object,
        default: () => {}
    }
})


const emit = defineEmits(['set-step'])

// 在线编辑Dialog控制
const showSelectMooc = ref(false);
let electiveCourseList = []; // 设置的非选修课课ID，选择慕课后需重新设置

const editRef = ref(null);
const coureNumRef = ref();
// 表单数据
let detail = ref({})
// 表单数据
let formData = ref({
    courseNum: 0
});
// 校验
const formRule = ref({
    courseNum: [
        { required: true, message: '请填写需要完成的选修类慕课数', trigger: 'blur' },
        { type: 'number', message: '请填写正整数' },
        {
            validator: (rule, value, callback) => {
                if (moocList.value.length && value>= 0 && value <= unMustStudy.value) {
                    callback();
                } else {
                    if(value<0) {
                        callback(new Error('请填写正整数'));
                    } else {
                        callback(new Error(`不能超过${unMustStudy.value}门`));
                    }
                }
            },
            trigger: 'blur'
        }
    ]
});

const moocList = ref([])

const topicRules = ref([])

// 必修个数
const mustStudy = computed(() => {
    return moocList.value.filter(item => item.required == 1).length
})

// 选修个数
const unMustStudy = computed(() => {
    return moocList.value.filter(item => item.required == 0).length
})

const topicRule = ref({
    itemContentType: '',
    itemType: '',
    name: '',
    rules: [
        {
            name: '',
            required: '',
            ruleContent: '',
            ruleType: '',
            taskId: '',
            taskItemId: ''
        }
    ],
    taskId: ''
})

// 获取修改query后的新地址
const watchPath = computed(() => {
    return queryToJson()
})

watch(() => watchPath.value, (val) => {
    if(watchPath.value.id) {
        getRulesByTopicId()
        getDetailData()
    }
}, {deep: true, immediate: true})

function selectMooc() {
    const list = [];
    moocList.value.forEach(item => !item.required && list.push(item.id));
    electiveCourseList = list;
    showSelectMooc.value = true;
}
// 在线编辑确认回调
function addMooc(content) {
    moocList.value = content.map(item => {
        return {
            ...item,
            required: electiveCourseList.includes(item.id) ? 0 : 1
        };
    })
}

function handleMooc(operate, item, index, scope) {
    switch (operate) {
        case 'up': 
            moocList.value[index] = moocList.value[index-1]
            moocList.value[index-1] = item
            break
        case 'down':
            moocList.value[index] = moocList.value[index+1]
            moocList.value[index+1] = item
            break
        case 'delete':
            moocList.value.splice(index, 1)
            break
    }
}
// 课件保存
async function save(){
    if(!moocList.value.length) {
        G_dispatchEvent('toast', { message: '请添加慕课', type: 'error'});
        return;
    }
    try {
        await editRef.value.validate();
        const taskContentCreateRequestList = moocList.value.map(item => ({
            contentType: 'mooc',
            id: item.taskContentId,
            contentId: item.id,
            name: item.title,
            taskId: watchPath.value.id,
            required: item.required
        }));
        G_transmit('addMoocTopicContent', {
            data: {
                taskContentCreateRequestList
            }
        }).then(() => {
            topicRules.value.length ? updateMoocTopicRule() : addMoocTopicRule();
            getContentMoocList();
        }).catch((err) => {
            console.eror(err);
        })
    } catch (error) {
        document.body.scrollIntoView({
            behavior: 'smooth',
            block: 'center'
        });
        coureNumRef.value.focus();
        console.error(error);
    }
}


// 设置步骤
function changeStep(step){
    emit('set-step', step)
    let id = watchPath.value.id
    window.history.replaceState('', '', `?id=${id}&step=${step}`);
}

// 返回课程详情
function goBack(){
    pageJump({
        name: route.name === 'strainMoocTopicCreate' ? 'strainTopicDetail' : 'topicDetail',
        params: {topicId: watchPath.value.id}
    });
}

function getBackUrl() {
    if(route.name === 'strainMoocTopicCreate') {
        return jumpHref.strain.strainTopicDetail(watchPath.value.id);
    } else {
        return jumpHref.strain.topicDetail(watchPath.value.id);
    }
}

// 获取编辑信息
function getDetailData() {
    return G_transmit('topicDetail', {
        queries: {
            id: watchPath.value.id
        }
    })
    .then(({ status, data }) => {
        if(!data.creatorFlag){
            G_dispatchEvent('toErrorPage', { title: '很抱歉，您暂时没有权限对该慕课进行编辑', code: 500, buttonLabel: '返回', target: getBackUrl()});
            return;
        }
        // if(data.state === -1){
        //     G_dispatchEvent('toErrorPage', { title: '该慕课专题已经被删除', code: 500});
        //     return;
        // }
        detail.value = data;
        return Promise.resolve(data);
    })
    .catch((err) => {
        if(err.status.code == '40000001'){
            G_dispatchEvent('toErrorPage', { title: '该慕课专题不存在', code: 500});
        }
        console.log(err, 'err');
    });
}

function getContentMoocList() {
    return G_transmit('getContentMoocList', {
        queries: {
            id: watchPath.value.id
        }
    })
    .then(({ status, data }) => {
        moocList.value = data || [];
    })
    .catch((err) => {
        if(err.status.code == '40000001'){
            G_dispatchEvent('toErrorPage', { title: '该慕课专题不存在', code: 500});
        }
        console.log(err, 'err');
    });
}
function getRulesByTopicId() {
    return G_transmit('getRulesByTopicId', {
        queries: {
            taskId: watchPath.value.id
        }
    })
    .then(({ status, data }) => {
        topicRules.value = data || []
        data && data.length && getTopicRule(data[0].id)
    })
    .catch((err) => {
        console.log(err, 'err');
    });
}
function getTopicRule(id) {
    return G_transmit('getTopicRule', {
        queries: {
            id
        }
    })
    .then(({ status, data }) => {
        topicRule.value = data || {}
        topicRule.value.rules = data.taskItemRuleVOS
        topicRule.value.rules[0].ruleContent = JSON.parse(topicRule.value.rules[0].ruleContent)
        formData.value.courseNum = topicRule.value.rules[0].ruleContent.ruleDetailDTOS[0].num
    })
    .catch((err) => {
        console.log(err, 'err');
    });
}
function addMoocTopicRule() {
    let ruleContent = {
        ruleType:'mooc',
        andOr:'',
        ruleDetailDTOS:[
            {
                andOr:'',
                num:formData.value.courseNum,
                studyTime:'',
                credit:'',
                hour:''
            }
        ]
    
    }
    topicRule.value.taskId = watchPath.value.id
    topicRule.value.rules[0].taskId = watchPath.value.id
    topicRule.value.rules[0].ruleContent = JSON.stringify(ruleContent)
    return G_transmit('addMoocTopicRule', {
        data: topicRule.value
    })
    .then(({ status, data }) => {
        G_dispatchEvent('toast', { message: '保存成功', type: 'success'});
        getRulesByTopicId()
        goBack()
    })
    .catch((err) => {
        console.log(err, 'err');
    });
}

function updateMoocTopicRule(id) {
    topicRule.value.rules[0].ruleContent.ruleDetailDTOS[0].num = formData.value.courseNum
    topicRule.value.rules[0].ruleContent = JSON.stringify(topicRule.value.rules[0].ruleContent)
    return G_transmit('updateMoocTopicRule', {
        data: topicRule.value
    })
    .then(({ status, data }) => {
        G_dispatchEvent('toast', { message: '保存成功', type: 'success'});
        getRulesByTopicId()
        goBack()
    })
    .catch((err) => {
        console.log(err, 'err');
    });
}

function delMoocTopicContent(data) {
    Confirm({
        title: '确认删除',
        text: '确认删除当前慕课吗?',
    }).then(res => {
        delCourseMaterial(data);
    }).catch(_err => {
        console.log(_err);
    })
    return G_transmit('delMoocTopicContent', {
        queries: {
            id: watchPath.value.id
        }
    })
    .then(({ status, data }) => {
        moocList.value = data
    })
    .catch((err) => {
        if(err.status.code == '40000001'){
            G_dispatchEvent('toErrorPage', { title: '该慕课专题不存在', code: 500});
        }
        console.log(err, 'err');
    });
}
onMounted(() => {
    getContentMoocList()
})
</script>

<style lang="scss" scoped>
.mooc-set-page {
    background: #fff;
    padding: 24px 20px 40px;
    border-radius: 0 0 4px 4px;
    // min-height: 600px;
    .topic-label {
        text-align: center;
    }
    .topic-title {
        font-size: 18px;
        font-weight: bold;
        color: #222222;
        line-height: 28px;
        text-align: center;
    }
}
.select-mooc-btn {
    width: 86px;
}
.selected-topic {
    margin: 24px 0 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .sort-left{
        display: inline-flex;
        align-items: center;
        flex: 1;
    }

}
.selected-mooc {
    font-size: 14px;
    color: #222222;
    line-height: 22px;
    .topic-num {
        margin: 0 3px;
        color: #47698C;
    }
}
.complete-rule {
    flex: 1;
    :deep(.el-form-item__label) {
        font-size: 14px;
        color: #666666;
    }
    .lesson-num {
        width: 90px;
        margin: 0 8px;
    }
    .error-item {
        width: 300px;
        transform: translate(-22px, -7px);
    }
}
.el-form-item {
    margin-bottom: 0
}
.submit{
    width:100%;
    margin: 40px auto;
    text-align: center;
    .el-button{
        width: 120px;
        height: 36px;
    }
}
.left-posi{
    text-align: left;
}
.button-left-margin{
    margin-left: 12px;
}

// :deep(.el-table__empty-block) {
//     height: 40px !important;
//     min-height: 20px !important;
// }
.t-empty-wrap {
    line-height: 14px;
    .add-mooc-btn {
        margin-top: 13px;
    }
}
</style>
